'''
Created on Apr 1, 2012

@author: pam
'''

import random
import sys,os
home_path=os.getcwd()+os.sep#Current path to this program
sys.path.append(home_path+"src"+os.sep+"pyvisa")
from ..visa import *

class Emulator:
    def __init__(self,add):
        self.address=add
    
    def write(self,command):
        print "Emulated: "+ self.address + " -> " + command
        
    def read(self):
        return ""

class GPIB_wrapper():
    def __init__(self,add,test):
        """
        - address: should be of the form GPIB0::x:INSTR
        - test: True or False
        """
        self.isTest=test #True or False
        self.address=add
        if self.isTest==True:
            self.wrapper=Emulator(add)
        else:
            self.wrapper=GpibInstrument(add)
    
    def strParse(self,word):
        if "e" in word:
            temp=word.split("e")
            return float(temp[0])*10**(int(temp[1]))
        elif word !='':
            return float(word)

    def write(self,command):
        self.wrapper.write(command)
        
    def read(self,type_of_reading):
        """
        type_of_reading: contains (list, float, scientific, string, int)
        """
        
        #Reading from the machine or simulating
        temp=self.wrapper.read()
        if self.isTest:
            if "scientific" in type_of_reading:
                temp=str(random.random())+"e-00"+str(random.randint(2,6))
            elif "float" in type_of_reading:
                temp=str(random.random())
            elif "int" in type_of_reading:
                temp=str(random.randint(1,100))
            elif "string" in type_of_reading:
                temp="test"
            
            if "list" in type_of_reading:
                temp = temp+","+temp+","
                
        #Processing the data
        if "list" in type_of_reading:
            temp=temp.split(",")
            if "scientific" in type_of_reading:
                temp=map(lambda x:self.strParse(x),temp[0:-2])
            elif "float" in type_of_reading:
                temp=map(lambda x:float(x),temp[0:-2])
            elif "float" in type_of_reading:
                temp=map(lambda x:int(x),temp[0:-2])
            elif "string" in type_of_reading:
                temp=temp[0:-2]
        else:
            if "scientific" in type_of_reading:
                temp=self.strParse(temp)
            elif "float" in type_of_reading:
                temp=float(temp)
            elif "int" in type_of_reading:
                temp=int(temp)
            elif "string" in type_of_reading:
                temp=temp[0:-2]
        
        return temp
            
